package validator.handle;

import java.lang.annotation.Annotation;
import java.util.Collection;

import validator.annotation.NotEmpty;
import validator.exception.ValidateException;

public class NotEmptyValidator implements Validator {

	@Override
	public boolean isValid(Class<?> clazz) {
		return clazz.isArray() || Collection.class.isAssignableFrom(clazz)
				|| CharSequence.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Annotation annotation, Object v) {
		int size = 0;
		if (v.getClass().isArray()) {
			size = ((Object[]) v).length;
		}
		if (CharSequence.class.isAssignableFrom(v.getClass())) {
			size = ((CharSequence) v).toString().trim().length();
		}
		if (Collection.class.isAssignableFrom(v.getClass())) {
			size = ((Collection<?>) v).size();
		}

		NotEmpty anno = (NotEmpty) annotation;
		if (size == 0)
			throw new ValidateException(anno.value());
	}
}
